package com.tuniu.agents.common.command.action;

import com.tuniu.agents.agent.Agent;
import com.tuniu.agents.agent.AgentManager;
import com.tuniu.agents.command.action.CallAgentAction;
import com.tuniu.agents.common.AgentsConstants;
import org.springframework.ai.chat.messages.UserMessage;
import reactor.core.publisher.Flux;

import java.util.List;
import java.util.Map;

/**
 * Default implementation of CallAgentAction that handles agent invocation.
 * This class is responsible for executing agent calls with the provided input and parameters.
 */
public class DefaultCallAgentAction extends CallAgentAction {

    /**
     * Manager for handling agent operations
     */
    private final AgentManager agentManager;

    /**
     * Constructor for DefaultCallAgentAction
     *
     * @param agentManager The manager responsible for agent operations
     */
    public DefaultCallAgentAction(AgentManager agentManager) {
        this.agentManager = agentManager;
    }

    /**
     * Executes the agent call with the provided input and parameters
     *
     * @param input   The input string to be processed by the agent
     * @param params  Parameters for the agent execution
     * @param context Context information for the execution
     * @return A Flux of strings representing the agent's response stream
     */
    @Override
    public Flux<String> execute(String input, Map<String, Object> params, Map<String, Object> context) {
        // Get the agent ID from parameters
        String agentId = (String) params.get(PARAM_AGENT_ID);
        // Get the conversation ID from context
        String conversationId = String.valueOf(context.get(AgentsConstants.AgentsConversationEnvironmentKey.CONVERSATION_ID));
        // Retrieve the agent instance
        Agent agent = agentManager.getAgent(agentId);
        // Check if a specific message is provided in parameters
        if (params.containsKey(DefaultOutputTextAction.KEY_MESSAGE)) {
            input = (String) params.get(DefaultOutputTextAction.KEY_MESSAGE);
        }
        // Stream the agent's response
        return agent.stream(conversationId, List.of(new UserMessage(input)), params);
    }
}
